<link rel="stylesheet" href="<?php echo URL::base() ?>media/vendor/css/style.css" type="text/css" media="all" />
<script src="<?php echo URL::base() ?>media/js/jquery-1.10.1.min.js"></script>

<link rel="stylesheet" href="<?php echo URL::base() ?>media/vendor/artdialog/skins/default.css" type="text/css" media="all" />
<script src="<?php echo URL::base() ?>media/vendor/artdialog/jquery.artDialog.js"></script>	 

<link href="<?php echo URL::base() ?>media/vendor/css/ui-lightness/jquery-ui-1.10.4.custom.css" rel="stylesheet">
<script src="<?php echo URL::base() ?>media/vendor/js/jquery-1.10.2.js"></script>
<script src="<?php echo URL::base() ?>media/vendor/js/jquery-ui-1.10.4.custom.js"></script>
<script src="<?php echo URL::base() ?>media/vendor/js/jquery.ui.datepicker-zh-TW.js"></script>
<style type="text/css">
.display_div{display:none}
.table tbody tr th{ font-weight:normal;}
</style>
<script type="text/javascript">

$(document).ready(function(){
	
	$.datepicker.setDefaults({ dateFormat: 'yy-mm-dd' });
	$(".delivery").datepicker();

	function dispaly_div(id)
	{
		var table = $("#table_"+id);
		if(table)
		{
			//alert(id);
			table.addClass('display_div');
		}
	}
	//获取选中的个数
	function get_num()
	{
		var sel_num = 0;
		$('input[name="selectnum[]"]').each(function()
		{
			if(this.checked)
			{
				sel_num++;
			}
		});
		$('#skucount').text(sel_num);

		return sel_num;
	}
	
	//设置供应商信息
	function set_provider(id,data)
	{
		$("#price_"+id).val(data.price);
		$("#delivery_"+id).val(data.delivery);
		$("#pay_way_"+id).val(data.paytype);//alert(data.paytype);
	}
	
	//获取一个SKU的相关信息
	function get_sku_purchase_details(id)
	{
		var sku = $("#sku_"+id).val();//alert(id);
		var sku_name = $("#sku_name_"+id).val();
		var supplier_id = $("#supplier_"+id).val();
		var price = $("#price_"+id).val();
		var prime_cost = $("#prime_cost_"+id).val();
		var warning_quantity = $("#warning_quantity_"+id).val();
		var quantity = $("#quantity_"+id).val();//alert(quantity);
		var tax_way = $("#tax_way_"+id).val();
		var pay_way = $("#pay_way_"+id).val();
		var remark = $("#remark_"+id).val();
		var transportation_expense = $("#transportation_expense_"+id).val();
		var arrive_date = $("#delivery_"+id).val();
		var tax_rate  = $("#tax_rate_"+id).val();
		if(Number(tax_rate )>100||Number(tax_rate)<0)
		{
				return false;
		}			
		var details = {"sku":sku,"sku_name":sku_name,"supplier_id":supplier_id,"prime_cost":prime_cost,"price":price,"warning_quantity":warning_quantity,"quantity":quantity,"pay_way":pay_way,"remark":remark,"transportation_expense":transportation_expense,"tax_way":tax_way,"arrive_date":arrive_date,"tax_rate":tax_rate};
		return details;
	}

	//选中
	$('input[name="selectnum[]"]').click(function(){
		get_num();
	});

	//供应商
	$('select[name="supplier_id[]"]').change(function(){

		var pre = 'supplier_';
		var id = $(this).attr('id').substr(pre.length);

		var details = get_sku_purchase_details(id);
		//alert(id);
		var sku = $('#sku_'+id).val();
		//alert(sku);
		var providerid = $(this).val();
		//alert(providerid);
		
		$.ajax({		
			type:'post',
			url:'<?php echo url::base(true)?>warning/getproviderproducts',
			dataType:'json',
			data:{"purchase":details},
			async:false,
			success:function(data)
			{
				// alert(data.provider_id);
				if(data)
				{
					set_provider(id,data);
				}
			},
			error:function()
			{
				alert('error');
			}
		});
	});

	
	//交期改变
	$('input[name="delivery[]"]').change(function(){
		
		var delivery = $(this).val().split("-");
		var newdate = new Date(delivery);
		var today = new Date();
		var delivery_new = (newdate.getTime() - today.getTime())/(1000*60*60*24);
		delivery_new =  Math.ceil(delivery_new);

		if(delivery_new < 0 )
		{
			alert('交货日期不能在今天之前');
			var today = new Date();
			today = today.getFullYear() +"-"+ (today.getMonth()+1) + "-"+ today.getDate();
			$(this).val(today);
			delivery_new = 0;
		}
		//delivery_
		
		var pre = 'delivery_';
		var id = $(this).attr('id').substr(pre.length);
		var supp_days = parseFloat($("#supp_days_"+id).text());
		var best = supp_days  -	delivery_new;
		var best_date = new Date();
		best_date.setDate(best_date.getDate()+best);
// 		alert(best_date);	
		var daysale = parseFloat($("#daysale_"+id).text());//alert(daysale);
		var q = parseInt((7-best)*daysale);

		$("#quantity_"+id).val(parseInt(q));
		$("#best_date_"+id).text(best_date.getFullYear() +"-"+ (best_date.getMonth()+1) + "-"+ best_date.getDate());
	});

		//计税方式改变
	$('select[name="tax_way[]"]').change(function(){
		var pre = 'tax_way_';
		var id = $(this).attr('id').substr(pre.length);
		
		var tax_way = $("#tax_way_"+id).val();
		
		if(tax_way == -1 || tax_way == 1)
		{
			$("#tax_rate_"+id).attr('readonly',false);
		}
		else
		{
			$("#tax_rate_"+id).val(0);
			$("#tax_rate_"+id).attr('readonly','readonly');			
		}
	});
	
	//选中全部
	$('#sel_all').click(function(){
		
		if(this.checked)
		{
			$('input[name="selectnum[]"]').each(function(){
				this.checked=true;
			});
			$('#sel_all_flag').text("全不选");
			get_num();
		}
		else
		{
			
			$('input[name="selectnum[]"]').attr('checked',false);
			$('#sel_all_flag').text("全选");
			get_num();
		}
	});

	//提交采购单
	function submit_purchase(purchase)
	{
			$.ajax({		
			type:'post',
			url:'<?php echo url::base(true)?>warning/purchase_exist',
			dataType:'json',
			data:{"purchase":purchase},
			async:false,
			success:function(data)
			{
				
				return data;
			},
			error:function()
			{
				return "error";
			}

			});
	}

	//提交审查
	$('#add_submit').click(function(){
		
		if(get_num() <= 0)
		{
			var tips = "至少选中一项";
			alert(tips);
			return false;
		}
		else
		{
			var flag = false;
			var sku_error = new Array();
			var purchase = new Array();

			$('input[name="selectnum[]"]').each(function(){

				if(this.checked)
				{
				var pre = 'sel_';
				var id = $(this).attr('id').substr(pre.length);
				var detail = get_sku_purchase_details(id);
				if(detail.quantity <= 0)
				{
					purchase.push(detail);
				}
				else
				{
					purchase.push(detail);
				}
			}
			});

			//if(sku_error)
			//{
			//
			//}

			$.ajax({		
			type:'post',
			url:'<?php echo url::base(true)?>warning/purchase_exist',
			dataType:'json',
			data:{"purchase":purchase},
			async:false,
			success:function(data)
			{
				
				if(data)
				{
					var html_string = "";
					var uri="purchases/selectpurchase/singledetail?p_id="
					html_string += "下列SKU已经存在未打印的采购单：";
					html_string +="<br/>";
					for(var i=0; i< data.length;i++)
					{
						// alert(data[i].sku);
						html_string += "SKU:";
						html_string += data[i].sku;
						html_string += "采购单编号："
						html_string += '<a href="<?php echo url::base(true)?>'+uri;
						html_string +=data[i].purchaseorder_id;
						html_string +='" target="_blank" >';
						html_string += data[i].purchaseorder_id;
						html_string +='</a>';
						html_string += "<br/>";
					};

					art.dialog({
    				content: html_string,
    				okVal:'仍然添加',
    				ok: function(){
    					flag =true;
    					$("#add_from").submit();    					
    				},
    				cancelVal: '关闭',
    				cancel: true //为true等价于function(){}
					});
					
				}
				else
				{
					flag = true;
				}
			},
			error:function()
			{
				alert('error');
			}

			});


			if(flag)
			{
				return true;
			}
			else
			{
				return false;
			}
		}
	});

	//修改目标时间段
	$('input[name="target_time[]"]').change(function(){

		var pre = 'target_time_';
		var id = $(this).attr('id').substr(pre.length);
		var target_time = $(this).val();//alert(target_time);
		var daysale = parseFloat($("#daysale_"+id).text());//alert(daysale);
		$("#quantity_"+id).val(parseInt(target_time * daysale));
	});

	//采购数量改变
	$('input[name="quantity[]"]').change(function(){

		var pre = 'quantity_';
		var id = $(this).attr('id').substr(pre.length);
		var quantity = $(this).val();//alert(target_time);
		if(isNaN(quantity))
		{
			quantity=0;
		}
		var daysale = parseFloat($("#daysale_"+id).text());//alert(daysale);
		var error   = $(this).parent().parent().prev().prev().children('td').eq(8).html();
		$("#target_time_"+id).val(parseInt((quantity - Number(error)*Number(daysale)) / daysale));
		//$("#target_time_"+id).val(parseInt(quantity / daysale));
	});

	$(".nowarning").click(function(){

		var flag = false;
		var pre = 'nowarning_';
		var id = $(this).attr('id').substr(pre.length);

		var data = new Array();
		var details = get_sku_purchase_details(id);
	    data.push(details);

	    $.ajax({		
			type:'post',
			url:'<?php echo url::base(true)?>warning/nowarning_one',
			dataType:'json',
			data:{"data":data,'status':1},
			async:false,
			success:function(data)
			{
				if(data)
				{
					flag = true;
				}
			},
			error:function()
			{
				alert('error');
			}
			});
		if(flag)
		{
			var nowcount = parseInt($('#skusum').val())-1;
			if(nowcount >= 0){
				$('#skusum').val(nowcount);
				$('#skunumber').html('本页总共有'+nowcount+'条SKU下单信息');
				dispaly_div(id);
				alert('操作成功');
			}
			//location.reload();
		}
		else{
			alert("操作失败");
		}
	    
		});

	
	//添加单个sku
	$(".addpurchase").click(function() {
	  var flag = false; 
	  var pre = 'addpurchase_';
	  var id = $(this).attr('id').substr(pre.length);

      var sku = $("#sku_"+id).val();
      var url = "<?php echo url::base(true)?>warning/index?sku="+sku;
      //var sku_name = '';
      //var sku
      // alert(id);
     var details = new Array();
		 var data = get_sku_purchase_details(id);
		 if(!data)
		 {
			 alert("税率超出范围(0～100)");return ;
		 }
     details.push(data);//alert(details);
     if(details[0].quantity<=0)
     {
     	alert("采购数量为0！");
     }
     else
     {
      $.ajax({		
			type:'post',
			url:'<?php echo url::base(true)?>warning/warningaddpurchase_one',
			dataType:'json',
			data:{"purchase":details},
			async:false,
			success:function(data)
			{
				// alert('ok');
				if(data)
				{
					dispaly_div(id);
      				var timer;
      				var uri="purchases/selectpurchase/singledetail?p_id="
      				var html_string = "添加成功";
      				html_string += "<br/>";
      				html_string += "采购单:";
      				html_string += data[0].purchaseorder_id;
					art.dialog({
  		 			 content: html_string,
   					init: function () {
    				var that = this, i = 5;
        			var fn = function () {
            		that.title(i + '秒后关闭');
           			 !i && that.close();
            		i --;
       				 };
        			timer = setInterval(fn, 1000);
       		 		fn();
    				},
    				ok:function(){
    				var url="<?php echo url::base(true)?>"+uri;
    				url = url+data[0].purchaseorder_id;
    				window.open(url);
    				},
		    		okVal:'查看',
		    		cancelVal:'关闭',
		    		cancel:function () {
		    			clearInterval(timer);
		    			//location.reload();
		    		},
		    		close: function () {
		    			clearInterval(timer);
		    			//dispaly_div(id);
		    			//location.reload();
		    			}
				}).show();
		      }
		      else
		      {
		      	alert("添加失败");
		      	//window.open(url);
		      }
				
			},
			error:function()
			{
				alert('error');
			}

			});
	}

  });

	$("#current_url").val(window.location.href);
	
});
function clearNoNum(obj)
{   
	obj.value = obj.value.replace(/[^\d.]/g,"");  //清除“数字”和“.”以外的字符  

	obj.value = obj.value.replace(/^\./g,"");  //验证第一个字符是数字而不是. 

	obj.value = obj.value.replace(/\.{2,}/g,"."); //只保留第一个. 清除多余的.   

	obj.value = obj.value.replace(".","$#$").replace(/\./g,"").replace("$#$",".");
}
</script>

								
								
<div>
<div>
	<input type="hidden" id="daystype" value="<?php if(isset($showback['days'])){ echo $showback['days'];}?>"/>
<form action="<?php echo url::base(true)?>warning/index" method="get" id="sel_form">
	<a class="btn" id="daystype_1" href="<?php echo url::base(true)?>warning/index?days=1">今日下单</a>
	<a class="btn" id="daystype_3" href="<?php echo url::base(true)?>warning/index?days=3">三日下单</a>
	<a class="btn" margin-right:10px;" id="daystype_7" href="<?php echo url::base(true)?>warning/index?days=7">七日下单</a>
<span>sku
<input type="text" placeholder="" name="sku" class="input-medium" value="<?php if(isset($showback['sku'])){ echo $showback['sku'];}?>"></span>
<!--  <span>供应商
<input type="text" placeholder="" name="supplier_name" class="input-medium"></span>-->
<button type="submit" class="btn btn-info" id="sel_submit">查询</button>
</form>
</div>
<script type="text/javascript">
var daystype=$("#daystype").val();//alert(daystype);
$("#daystype_"+daystype).addClass("btn-info");
</script>
<?php if(true){?>
<span>当前采购人员<?php echo user::active_user()->name?></span>
<span id='skunumber'>本页总共有<?php echo count($skulists);?>条SKU下单信息</span>
<input type="hidden" value="<?php echo count($skulists);?>" id="skusum">
<a href="<?php echo url::base(true) ?>warning/warning_sku_lists" target="_blank" class="btn btn-info">不下单的SKU</a>
<?php }?>
</div>
<div style=" margin-top:20px;">
<form action="<?php echo url::base(true)?>warning/warningaddpurchase" method="post" id="add_from" autocomplete="off">
<?php if(isset($skulists) and !empty($skulists)){
foreach ($skulists as $num => $sku){
?>

<div id="table_<?php echo $sku['sku']?>">
<table class="table table-bordered" style="table-layout:fixed;">
<tbody>
										<?php 
										$provider_lists = Service_warningcount::get_provider_lists($sku['sku']);
										?>
												<tr style=" background-color:#4EA392;color:#fff;">
														<th>
															序号
														</th>
														<th style="width:70px;">
															SKU
														</th>
														<th>
															中文名称
														</th>
														<th>
							
															下单提示
														</th>
														<th  style="width:94px;">
															实际可用库存
														</th>
														<th  style="width:78px;">
															在途库存
														</th>
														<th style="width:78px;">
															日均销量
														</th>
														<th  style="width:78px;"> 
															可支持天数
														</th>
														<th  style="width:65px;">
															误差天数
														</th>
														<th>
															税率
														</th>
													</tr>
													
													<tr>
														<?php 
														$product_data = basic::load_sku_info($sku['sku']);	
														?>
														<td>
															<!-- 
															<input type="checkbox" name="selectnum[]" class="sel_num"
															id="sel_<?php echo $sku['sku']?>"
															value="<?php echo $num;?>"
															> -->
															<?php echo $num+1?>
														</td>
														
														<td>
														<!-- SKU -->
															<input type="hidden" name="sku[]" 
															id="sku_<?php echo $sku['sku'];?>"
															value="<?php echo $sku['sku']?>" readonly="readonly">
															<a href="<?php echo url::base(true).'advancewarning/index?sku='.$sku['sku']?>"
																target="_blank">
																<?php echo $sku['sku']?></a>
														</td>

														<td>
														<!-- 名称 -->
														<input type="hidden" name="sku_name[]" value="<?php echo $product_data['products_name_cn']?>">
														<?php echo $product_data['products_name_cn']?>
														</td>

														<td>
															<?php echo service_warning::get_warning_tips($sku); ?>

														</td>

														<td>
														<?php echo $sku['inventory']['actual_available_num']?>												
														</td>
														
														<td>
														<?php echo $sku['inventory']['pp_num']?>
														</td>

														<td>
														<span id="daysale_<?php echo $sku['sku']?>">
														<?php echo round($sku['daysales'],2)?>
														<span>
														</td>

														<td>
															<span id="supp_days_<?php echo $sku['sku']?>">
															<?php 
															//可支持天数
																echo round($sku['supp_days'],2);
															?>				
															</span>										
														</td>
														<td>
															 <?php echo round($sku['delivery'] - $sku['supp_days'],2) ?> 
														</td>

														<td>
															<input type="text" class="input-mini" name="tax_rate[]" id="tax_rate_<?php echo $sku['sku']?>"  onkeyup="clearNoNum(this)" value=0 readonly="readonly" />%
														</td>
													</tr>

													<tr  style="background-color:rgba(129,208,177,.3)"> 
														<th>
															最佳下单日期
														</th>
														<th>
															目标时间段
														</th>
														<th>
															采购量
														</th>
														<th>
															预交期
														</th>
														<th>
															供应商
														</th>
														<th>
															单价
														</th>
														<th>
															计税方式
														</th>
														<th>
															付款方式
														</th>
														<th>
															运费
														</th>
														<th>
															操作
														</th>
														
													</tr>

														<tr>
														<td >
															<!-- 最佳下单日期 -->
															<?php //echo round($sku['best'],0)?>
															<span id="best_date_<?php echo $sku['sku']?>">
															<?php echo (floor($sku['best'])<90)?date('Y-m-d',strtotime(floor($sku['best']).'days')):''?>
															</span>		
														</td>
														<td>
															<!-- 目标时间段 -->
															<input type="text" style="width:30px;" name="target_time[]" 
															id="target_time_<?php echo $sku['sku']?>" readonly="readonly"
															value="<?php echo $sku['target_time']?>" class="input-mini"/>/天
														</td>
														<td>
															<!-- 采购量 -->
															<input type="hidden" style="width:50px;" value="<?php echo $sku['daysales']*$sku['target_time']?>"
															name="warning_quantity[]" id="warning_quantity_<?php echo $sku['sku']?>">
															<input id="quantity_<?php echo $sku['sku']?>"
															value="<?php echo round($sku['daysales']*$sku['target_time']+($sku['delivery'] - $sku['supp_days'])*$sku['daysales'],0)?>"
															type="text" name="quantity[]"  class="input-mini"/>
														</td>
														<td>
															<!-- 交货日期 -->
															<input type="text" name="delivery[]" style="width:72px;" readonly="readonly" class="input-medium delivery"
															value="<?php echo date('Y-m-d',strtotime($provider_lists[0]['delivery'].'days'))?>"
															id="delivery_<?php echo $sku['sku']?>"/>
														</td>
														<td>
															<!-- 供应商 -->
															<select style="width:95px;" class="input-medium" name="supplier_id[]" 
															id="supplier_<?php echo $sku['sku']?>"/>供应商
															<?php foreach ($provider_lists as $provider){?>
															<option value="<?php echo $provider['iproviderID']?>">
														<?php echo $provider['vProviderName']?>
															</option>	
															<?php }?>
															</select>
														</td>
														<td>
															<!-- 价格 -->
															<input type="hidden" name="prime_cost[]" value="<?php echo $product_data['products_values']?>"
															id="prime_cost_<?php echo $sku['sku']?>"/>
															<input type="text" name="single_price[]" class="input-mini" value="<?php echo $provider_lists[0]['price']?>"
															id="price_<?php echo $sku['sku']?>"/>
														</td>
														<td>
															<!-- 计税方式 -->
															<select class="input-mini" style="width:78px;" name="tax_way[]"   
															id="tax_way_<?php echo $sku['sku']?>"/>计税方式
															<?php foreach ($tax_ways as $tax_way){?>
															<option value="<?php echo $tax_way['id']?>">
														<?php echo $tax_way['tax_way']?>
															</option>	
															<?php }?>
															</select>
														</td>

														<td>
															<!-- 付款方式 -->
															<select class="input-mini" style="width:78px;" name="pay_way[]" 
															id="pay_way_<?php echo $sku['sku']?>" />付款方式
															<?php foreach ($pay_ways as $pay_way){?>
															<option value="<?php echo $pay_way['id']?>"
															<?php if(trim($pay_way['pay_way']) == trim($provider_lists[0]['payment'])){
															echo "selected='selected'";}?> >
														<?php echo $pay_way['pay_way']?>
															</option>	
															<?php }?>
															</select>
															<?php //echo $provider_lists[0]['payment'];?>
														</td>

														<td>
															<!-- 运费 -->
															<input style="width:50px;" type="text" id="transportation_expense_<?php echo $sku['sku']?>"
															name="transportation_expense[]" class="input-mini"/>
														</td>
														<td>
														<input style="margin-bottom:3px;" type="button" value="确定采购" class="btn btn-info addpurchase" id="addpurchase_<?php echo $sku['sku']?>">
														<input type="button" value="不下单" class="btn btn-info nowarning" id="nowarning_<?php echo $sku['sku']?>">
														</td>
													</tr>

											</table></div>
														<?php }}?>
												
											<!--  
														<input type="checkbox" id="sel_all"/>
														<span id="sel_all_flag">全选</span>														
														<span>已经选择<span id="skucount">0</span>个SKU</span><br/>

														-->
														<input type="hidden" name="current_uri" id="current_url" value="<?php echo url::base(true)?>">
														
<!--  
														<input class="btn btn-info" type="submit" id="add_submit" value="添加">
														-->
														</form>
														<a href="">上一页</a><a href="">下一页</a>
														

</div>
									
							

  
